<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>章节管理</el-breadcrumb-item>
      <el-breadcrumb-item>章节列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="5">
          <el-input
            placeholder="请输入章节名"
            v-model="queryParam.chapterName"
            clearable
            @clear="searchChapter">
            <el-button slot="append" icon="el-icon-search" @click="searchChapter"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" v-if="addOrNew" @click="addDialogVisible = true">添加章节</el-button>
          <el-button type="primary" v-else @click="newLevelChapter">开启学年</el-button>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" v-if="sort" @click="openSortDisabled">拖动排序</el-button>
          <el-button type="primary" v-else @click="closeSortDisabled">排序完毕</el-button>
        </el-col>
      </el-row>
      <!-- 章节列表区域 -->
      <el-table :data="tableData" border stripe row-key="chapterId">
        <el-table-column v-if="sortPreIcon"><i class="el-icon-s-operation"></i></el-table-column>
        <el-table-column v-else type="index" />
        <el-table-column label="章节名称" prop="chapterName" />
        <el-table-column label="创建时间" prop="ctime" />
        <el-table-column label="操作" >
          <template v-slot="{row}">
            <el-button size="mini" type="primary" @click="showEditChapterDialog(row.chapterId)">
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="removeChapterById(row.chapterId)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <pagination 
        v-show="total>0" 
        :total="total" 
        :page.sync="queryParam.pageIndex" 
        :limit.sync="queryParam.pageSize"
        @pagination="getChapterList"/>
    </el-card>
    <!-- 添加章节的对话框 -->
    <el-dialog
    title="添加章节"
    :visible.sync="addDialogVisible"
    width="50%"
    @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form 
      :model="addForm" 
      :rules="addFormRules" 
      ref="addFormRef" 
      label-width="100px" >
        <el-form-item label="章节名" prop="chapterName">
          <el-input v-model="addForm.chapterName"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addChapter">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑章节的对话框 -->
    <el-dialog
    title="编辑章节"
    :visible.sync="editDialogVisible"
    width="50%">
      <!-- 内容主体区域 -->
      <el-form 
      :model="editForm" 
      :rules="editFormRules" 
      ref="editFormRef" 
      label-width="100px" >
        <el-form-item label="章节名" prop="chapterName">
          <el-input v-model="editForm.chapterName"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editChapter">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import chapterApi from '@/api/chapter'
import Pagination from '@/components/Pagination'
import Sortable from 'sortablejs'

export default {
  components: { Pagination, Sortable },
  data() {
    return {
      // 查询章节的参数
      queryParam: {
        chapterName: '',
        userLevel: undefined,
        pageIndex: undefined,
        pageSize: undefined,
      },
      // 控制是添加按钮还是新启一学年的按钮, 默认添加
      addOrNew: true,
      // 获取到的章节总条数
      total: 0,
      // 表格数据绑定的对象
      tableData: [],
      // 控制添加章节对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        chapterName: '',
        userLevel: undefined
      },
      // 添加表单的验证规则对象 
      addFormRules: {
        chapterName: [
          { required: true, message: '请输入章节名称', trigger: 'blur' },
        ]
      },
      // 控制编辑用户对话框的显示与隐藏
      editDialogVisible: false,
      // 编辑章节的表单数据
      editForm: {
        chapterId: undefined,
        chapterName: '',
      },
      // 编辑表单的验证规则对象 
      editFormRules: {
        chapterName: [
          { required: true, message: '请输入章节名称', trigger: 'blur' },
        ]
      },
      // 控制拖动排序的按钮显示与隐藏
      sort: true,
      // 拖动效果实例
      sortable: undefined,
      // 拖动图标
      sortPreIcon: false,
      tempShow: true
    }
  },
  props: {
    mainLevel: {
      type: Number
    }
  },
  watch: {
    mainLevel() {
      this.addForm.userLevel = this.mainLevel
      this.queryParam.userLevel = this.mainLevel
      this.tempShow = true
      console.log(this.tempShow);
      this.searchChapter()
    }
  },
  created() {
    // init页面
    this.searchChapter()
  },
  methods: {
    // 打开拖动开关
    openSortDisabled() {
      this.sortPreIcon = true
      this.sort = false
      this.drag()
    },
    closeSortDisabled() {
      this.sortable.destroy()
      this.sortPreIcon = false
      this.sort = true
      // 后端保存排序
      chapterApi.chapterSort(this.tableData).then(data => {
        if (data.code === this.ok.code) {
          this.$message.success(data.message)
          this.initChapter(this.mainLevel)
          this.getChapterList()
        } else {
          this.$message.error(data.message)
        }
      })
    },
    // 拖动
    drag() {
      // 首先获取需要拖拽的dom节点
      const el = document.querySelector('.el-table__body-wrapper tbody');
      this.sortable = Sortable.create(el, {
        draggable: ".el-table__row",
        disabled: false, // 是否开启拖拽
        ghostClass: 'sortable-ghost', //拖拽样式
        animation: 150, // 拖拽延时，效果更好看
        group: { // 是否开启跨表拖拽
          pull: false,
          put: false
        },
        onEnd: (e) => { // 这里主要进行数据的处理，拖拽实际并不会改变绑定数据的顺序，这里需要自己做数据的顺序更改
          let arr = this.tableData; // 获取表数据
          arr.splice(e.newIndex, 0, arr.splice(e.oldIndex, 1)[0]); // 数据处理
          this.$nextTick(function () {
            this.tableData = arr; 
          });
        }
      });
    },
    // 条件搜索章节
    searchChapter() {
      this.queryParam.userLevel = this.mainLevel
      this.queryParam.pageIndex = this.page.index
      this.queryParam.pageSize = this.page.size
      this.getChapterList()
    },
    // 获取章节列表
    getChapterList() {
      let _this = this
      chapterApi.getChapterList(_this.queryParam).then(data => {
        if (data.code === _this.ok.code) {
          _this.tableData = data.response.list
          if (_this.tableData.length === 0) {
            // 改变按钮
            if (_this.tempShow) {
              _this.addOrNew = false
            } else {
              _this.addOrNew = true
            }
          } else {
            _this.addOrNew = true
          }
          _this.tempShow = false
          _this.total = data.response.total
          _this.queryParam.pageIndex = data.response.pageNum
        }        
      })
    },
    // 新启一学年
    newLevelChapter() {
      chapterApi.newLevelChapter(this.mainLevel).then(re => {
        if (re.code === this.ok.code) {
          this.$message.success(re.message)
          this.searchChapter()
        } else {
          this.$message.error('请保证上一学年已开课')
        }
        this.initChapter(this.mainLevel)
      })

    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮添加新章节
    addChapter() {
      let _this = this
      this.$refs.addFormRef.validate(valid => {
        if (!valid) {
          return
        }
        _this.addForm.userLevel = _this.mainLevel
        chapterApi
          .editChapter(_this.addForm)
          .then(data => {
            if (data.code === _this.ok.code) {
              // 关闭对话框
              _this.addDialogVisible = false
              // 重新获取表格数据
              _this.searchChapter()
              _this.initChapter(this.mainLevel)
              // 提示成功信息  TODO 会重复刷新消息通知
              _this.$message.success(data.message)
            } else {
              _this.$message.error(data.message)
              _this.$refs.addFormRef.resetFields()
            }
          })
      })
    },
    // 展开编辑章节对话框
    showEditChapterDialog(chapterId) {
      let _this = this
      // 根据章节id获取章节
      chapterApi
        .getChapterById(chapterId)
        .then(data => {
          if (data.code === _this.ok.code) {
            _this.editForm = data.response
            _this.editDialogVisible = true
          } else {
            _this.$message.error(data.message)
          }
        })
    },
    // 点击按钮，修改用户信息
    editChapter() {
      let _this = this
      this.$refs.editFormRef.validate(valid => {
        if (!valid) {
          return
        }
        // 发起编辑用户的请求
        chapterApi
          .editChapter(_this.editForm)
          .then(data => {
            if (data.code === _this.ok.code) {
              // 提示成功信息
              _this.$message.success(data.message)
              // 关闭对话框
              _this.editDialogVisible = false
              // 重新获取表格数据
              _this.searchChapter()
              _this.initChapter(this.mainLevel)
            } else {
              _this.$message.error(data.message)
              _this.editDialogVisible = false
            }
          })
      })
    },
    // 根据id删除对应的章节信息
    async removeChapterById(chapterId) {
      // 弹窗询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该章节, 是否继续?', 
        '提示', 
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      chapterApi
        .removeChapterById(chapterId)
        .then(data => {
          if (data.code === this.ok.code) {
            // 提示成功信息
            this.$message.success(data.message)
            // 重新获取表格数据
            this.searchChapter()
            this.initChapter(this.mainLevel)
          } else {
            this.$message.error(data.message)
          }
        })
    },
    ...mapActions('chapter', { initChapter: 'initChapter' }),
  },
  computed: {
    ...mapState('page', {
      page: state => state.page
    }),
    ...mapState('resCode', {
      ok: state => state.OK
    }),
    ...mapState('enumItem', {
      userLevelEnum: state => state.user.userLevelEnum,
    })
  }
}
</script>

<style lang="less" scoped>

</style>>
